package edu.zjut.hjg.saas.web.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.document.AbstractJExcelView;

import edu.zjut.hjg.saas.biz.model.Kindergarten;
import edu.zjut.hjg.saas.biz.model.PriceType;
import edu.zjut.hjg.saas.biz.model.Subscribe;
import edu.zjut.hjg.saas.biz.model.Tenant;
import edu.zjut.hjg.saas.biz.service.EmailService;
import edu.zjut.hjg.saas.biz.service.SubscribeService;
import edu.zjut.hjg.saas.biz.service.TenantService;
import edu.zjut.hjg.saas.biz.support.AppStatus;

@Controller
@RequestMapping("/admin/subscribe")
public class SubscribeManangeController {
    private static final int PAGE_SIZE = 20;

    @Autowired
    private SubscribeService subscribeService;

    @Autowired
    private TenantService    tenantService;

    @Autowired
    private EmailService     emailService;

    @RequestMapping("/list.htm")
    public String list(
                       @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                       Model model, AppStatus status) {
        if (page < 1) {
            page = 1;
        }
        model.addAttribute("paginated", subscribeService.listByAppStatus(status, PAGE_SIZE, page));
        String queryUri = "/admin/subscribe/list.htm";
        String reportUri = "/admin/subscribe/report.htm?page=" + page;
        if (status != null) {
            queryUri = queryUri + "?status=" + status;
            reportUri = reportUri + "&status=" + status;
            model.addAttribute("status", status);
        }
        model.addAttribute("queryUri", queryUri);
        model.addAttribute("reportUri", reportUri);
        return "admin/subscribe";
    }

    @RequestMapping("/report.htm")
    public ModelAndView report(
                               @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                               AppStatus status) {
        if (page < 1) {
            page = 1;
        }
        List<Subscribe> subscribes = subscribeService.listByAppStatus(status, PAGE_SIZE, page)
                .getValues();
        return new ModelAndView(new ReportView(), "subscribes", subscribes).addObject("page", page);
    }

    @RequestMapping("/ajax/sendMail.htm")
    @ResponseBody
    public Map<String, Object> sendMail(@RequestParam("tenantId") int tenantId) {
        Map<String, Object> result = new HashMap<String, Object>();
        Tenant tenant = tenantService.findById(tenantId);
        if (tenant == null) {
            result.put("success", true);
            result.put("message", "发送邮件失败: 租户不存在！");
        }
        emailService.sendEmail(tenant.getEmail(), "您的幼儿网站状态提醒", rendEmail(tenant));
        result.put("success", true);
        return result;
    }

    public class ReportView extends AbstractJExcelView {

        @SuppressWarnings("unchecked")
        @Override
        protected void buildExcelDocument(Map<String, Object> model, WritableWorkbook workbook,
                                          HttpServletRequest request, HttpServletResponse response)
                throws Exception {
            response.addHeader("Content-Disposition", "attachment; filename=report.xls");

            List<Subscribe> subscribes = (List<Subscribe>) model.get("subscribes");
            int page = (Integer) model.get("page");
            WritableSheet sheet = workbook.createSheet("第 " + page + " 页", 0);
            sheet.addCell(new Label(0, 0, "租户的网站租用信息"));
            sheet.mergeCells(0, 0, 9, 0);

            sheet.addCell(new Label(0, 1, "租户"));
            sheet.addCell(new Label(1, 1, "余额(元)"));
            sheet.addCell(new Label(2, 1, "网站域名"));
            sheet.addCell(new Label(3, 1, "网站状态"));
            sheet.addCell(new Label(4, 1, "城市"));
            sheet.addCell(new Label(5, 1, "租期开始时间"));
            sheet.addCell(new Label(6, 1, "租期结束时间"));
            sheet.addCell(new Label(7, 1, "计价类型"));
            sheet.addCell(new Label(8, 1, "单价(元)"));
            for (int i = 0; i < subscribes.size(); i++) {
                Subscribe subscribe = subscribes.get(i);
                Kindergarten app = subscribe.getKindergarten();
                Tenant tenant = app.getTenant();
                PriceType priceType = subscribe.getPriceType();
                sheet.addCell(new Label(0, i + 2, tenant.getLoginId()));
                sheet.addCell(new jxl.write.Number(1, i + 2, tenant.getBalance()));
                sheet.addCell(new Label(2, i + 2, app.getSiteDomain()));
                sheet.addCell(new Label(3, i + 2, app.getStatus().getName()));
                sheet.addCell(new Label(4, i + 2, app.getCity().getName()));
                sheet.addCell(new Label(5, i + 2, DateFormatUtils.format(app.getStartDate(),
                        "yyyy-MM-dd")));
                sheet.addCell(new Label(6, i + 2, DateFormatUtils.format(app.getEndDate(),
                        "yyyy-MM-dd")));
                sheet.addCell(new Label(7, i + 2, priceType.getChargeType().getName()));
                sheet.addCell(new Label(8, i + 2, priceType.getPrice() + " / "
                        + priceType.getUnit()));
            }
        }
    }

    private String rendEmail(Tenant tenant) {
        StringBuffer buffer = new StringBuffer("尊敬的用户");
        buffer.append(tenant.getLoginId());
        buffer.append("(");
        buffer.append(tenant.getName());
        buffer.append(")，您好：<br />");
        buffer.append("您的幼儿园网站处于停用状态，请及时开通。");
        buffer.append("<br />");
        buffer.append("特此提醒，该邮件为系统邮件，请勿回复！");
        return buffer.toString();
    }
}
